const express = require("express");
const Users = require("../models/users");
const router = new express.Router();
const user_name_reg = /^[A-Za-z0-9_]{5,16}$/;
const password_reg = /^[A-Za-z0-9.]{0,20}$/;
router.post("/register",async(req,res)=>{
    const {user_name,password} = req.body;
    if(user_name_reg.test(user_name)&& password_reg.test(password)){
        try{
            await Users.create(req.body);
            res.send("注册成功");
        }catch(e){
            console.log(e);
            res.send("网络延迟");
        }
    }else{
        res.send("不符合");
    }
})
router.post("/login",async(req,res)=>{
    const {user_name,password} = req.body;
    if(user_name_reg.test(user_name) && password_reg.test(password)){
        try{
            const user = await Users.findOne({user_name});
            if(user){
                if(user.password == password){
                    res.send("登陆成功");
                }else{
                    res.send("密码错误")
                }
            }else{
                res.send("用户不存在")
            }
        }catch(e){
            console.log(e);
            res.send("网络延迟")
        }

    }else{
        res.send("用户名或密码格式不正确")
    }
})
module.exports = router;